package com.test.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.beetl.core.Template;

import com.test.DbHelp;
import com.test.core.CreatCore;
import com.test.core.WebCreat;
import com.test.model.PieBean;
import com.test.model.PieCharsBean;

/**
 * Servlet implementation class PieServlet
 */
public class PieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PieServlet() {
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		Map<String, String[]> map = request.getParameterMap();
		PieCharsBean pcb=new PieCharsBean();
		try {
			BeanUtils.populate(pcb, map);
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		 
		//response.setCharacterEncoding("UTF-8");
	
		Template temp = WebCreat.getWebCreat().getTemplate(CreatCore.TEMPLATE).getTemplate("pie.chars");
	//	String sql="SELECT name,num as value FROM test";
		List<Map<String, Object>> list = DbHelp.getDbHelp().getTenmplate().queryForList(pcb.getSql());
		List<PieBean> listPie=new ArrayList<PieBean>();
		for(Map<String, Object> m:list){
			 PieBean pb=new PieBean();
			 try {
				BeanUtils.populate(pb, m);
				 listPie.add(pb);
				
			} catch (IllegalAccessException e) {
				response.getWriter().print(e.toString());
				e.printStackTrace();
				
			} catch (InvocationTargetException e) {
				response.getWriter().print(e.toString());
				e.printStackTrace();
			}finally{
				//response.getWriter().close();
			}
		}
		 temp.binding("list", listPie);
		 temp.binding("text",pcb.getText() );
		 temp.binding("subtext",pcb.getSubtext());
		 temp.binding("name",pcb.getName());
		 response.getWriter().print(temp.render());
		 response.getWriter().close();
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 this.doGet(request, response);
	}

}
